package xyz.talentboy.TL.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import xyz.talentboy.TL.bean.TuRingReq;
import xyz.talentboy.TL.bean.TuRingRes;
import xyz.talentboy.common.util.Md5;


@Component
public class TuRingUtil {
	
	@Autowired
	RestTemplate restTemplate;
	
	@Value("${TL.apiUrl}")
	private String url;
	
	@Value("${TL.apiKey}")
	private String key;
	
	@Value("${TL.secret}")
	private String secret;
	
	public TuRingRes postTL(String info,String userId){	
		return postTLS(info, userId, null);
	}
	
	public TuRingRes postTL(String info,String userId,String loc){			
		return postTLS(info, userId, loc);
	}
	
	/**
	 * 请求数据加密
	 * @param info
	 * @param userId
	 * @param loc
	 * @return
	 */
	private TuRingRes postTLS(String info,String userId,String loc){
		TuRingReq tuRingReq = new TuRingReq();
		tuRingReq.setInfo(info);
		tuRingReq.setKey(this.key);
		tuRingReq.setUserid(userId);
		String data = JSON.toJSONString(tuRingReq);
		//获取时间戳
		String timestamp = String.valueOf(System.currentTimeMillis());
		//生成密钥
		String keyParam = secret+timestamp+this.key;
		String key = Md5.MD5(keyParam);		
		//加密
		Aes mc = new Aes(key);
		data = mc.encrypt(data);		
		//封装请求参数
		JSONObject json = new JSONObject();
		json.put("key", this.key);
		json.put("timestamp", timestamp);
		json.put("data", data);
		//请求图灵api	
		ResponseEntity<String> responseTL = restTemplate.postForEntity(this.url, json.toString(), String.class);
		TuRingRes tuRingRes = JSON.parseObject(responseTL.getBody(), TuRingRes.class);
		return tuRingRes;
	}
	
}
